/**
 * @desc 获取需要展示的菜单列表
 */
export const findShowMenu = (menu) => {
  if (!menu || menu.length === 0) return
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].hidden && !['Mch', 'Sp', 'System'].includes(menu[i].code)) {
      menu.splice(i, 1)
      i--
    } else {
      findShowMenu(menu[i].children)
    }
  }
}

/**
 * @desc 获取需要展示的菜单第一个
 */
export const findMenuFirstChild = (menu) => {
  for (let i = 0; i < menu.length; i++) {
    if (!menu[i].children || menu[i].children.length === 0) {
      return menu[i]
    } else {
      return findMenuFirstChild(menu[i].children)
    }
  }
}

/**
 * @desc 获取第一个路由
 */
export const findFirstRoutePath = (routes, path = '') => {
  for (let i = 0; i < routes.length; i++) {
    if (!routes[i].children || routes[i].children.length === 0) {
      path += routes[i].path
      return path
    } else {
      path += routes[i].path
      return findFirstRoutePath(routes[i].children, path)
    }
  }
}

/**
 * @desc 处理菜单列表to {code:code菜单信息}
 */
export const menusTreeToMap = (menus) => {
  let menusList = {}
  menus.forEach(v => {
    const menu = Object.assign({}, v)
    let children = []
    if (v.children && v.children.length > 0) {
      children = menusTreeToMap(menu.children)
    }
    delete menu.children
    menusList[menu.code] = menu
    menusList = Object.assign(menusList, children)
  })
  return menusList
}

/**
 * @desc 处理菜单列表to [code菜单信息]
 */
export const menusTreeToList = (menus, parent) => {
  let menusList = []
  for (let i = 0; i < menus.length; i++) {
    let menu = menus[i]
    menu = Object.assign({}, menu)
    let children = []
    if (menu.children && menu.children.length > 0) {
      children = menusTreeToList(menu.children, menu)
    }
    delete menu.children
    menu.parent = parent
    menusList.push(menu)
    menusList = menusList.concat(children)
  }
  return menusList
}

/**
 * @desc 过滤异步路由
 */
export const filterAsyncRoutes = (routes, menusMap = {}) => {
  const menusCodeMap = Object.keys(menusMap)
  for (let i = routes.length - 1; i >= 0; i--) {
    const v = routes[i]
    if (v.children && v.children.length > 0) {
      filterAsyncRoutes(v.children, menusMap)
    } else if (!menusCodeMap.includes(v.name)) {
      routes.splice(i, 1)
    } else {
      // 把菜单信息同步到路由meta
      v.meta = Object.assign(v.meta || {}, menusMap[v.name] || {})
    }
  }
}

/**
 * @desc 找tree父节点
 */
export const findTreeParent = (nodeList, nodeId) => {
  const ans = []
  for (let i = 0; i < nodeList.length; i++) {
    if (nodeList[i].id === nodeId) {
      if (nodeList[i].parentId === -1 || nodeList[i].parentId === 0) {
        // 根节点
        return [nodeList[i]]
      } else {
        // 非根节点
        ans.push(nodeList[i])
        return findTreeParent(nodeList, nodeList[i].parentId).concat(ans)
      }
    }
  }
  return ans
}
